<script setup lang="ts">
import type { VxeGridProps, VxePagerEvents, VxeTableEvents } from 'vxe-table'
import { putRole } from '@fl/api/iam-api/user-manage'
import { SearchTable, SubmitBtn } from '@fl/components'
import { PlusDialog } from 'plus-pro-components'

const props = withDefaults(defineProps<{
    roleRow: any,
    roleOptions: any
}>(), {
    roleRow: '',
    roleOptions: []
})
const { roleRow, roleOptions } = toRefs(props)

const emits = defineEmits(['update:show'])
const show = defineModel<boolean>('show', { required: true, default: false })
const tableRef = ref()
const chooseIds = ref<string[]>([])

// 选择/关闭弹窗
function confirm() {
    if (chooseIds.value.length === 0) {
        ElMessage({
            message: '至少选择一项',
            type: 'warning',
        })
        return
    }
    const ids = chooseIds.value.reduce((pre, cur) => {
        pre += `${cur},`
        return pre
    }, '')
    const params = {
        userId: roleRow.value.userId,
        roleIds: ids.slice(0, ids.length - 1)
    }
    putRole(params).then(res => {
        console.log('res', res)
        ElMessage.success('操作成功')
    })
    close()
}
function close() {
    emits('update:show', false)
    const $table = tableRef.value?.tableInstance
    $table.clearCheckboxRow()
}

// 选择一组广告
const handleCheckChange: VxeTableEvents.CheckboxChange = () => {
    const $table = tableRef.value?.tableInstance
    if ($table) {
        const records = $table.getCheckboxRecords()
        chooseIds.value = toRaw(records).reduce((pre: any, cur: any) => {
            pre.push(cur.roleId)
            return pre
        }, [])
    }
}

const gridOptions = reactive<VxeGridProps>({
    columns: [
        { type: 'checkbox', width: 50 },
        { title: '序号', type: 'seq', width: 50 },
        { field: 'roleId', title: '角色编号' },
        { field: 'roleName', title: '角色名称' },
        { field: 'roleKey', title: '权限字符' },
        { field: 'createTime', title: '创建时间' },
    ],
    checkboxConfig: {
        highlight: true, // 选择高亮
        trigger: 'row'
    },
})
</script>

<template>
    <PlusDialog v-model="show" :title="'分配角色'" width="60%" @close="close" :has-footer="false">
        <div>用户昵称：{{ roleRow.nickName }} 登录账号：{{ roleRow.userName }}</div>
        <SearchTable ref="tableRef" v-bind="gridOptions"
            :data="roleOptions" @checkbox-change="handleCheckChange">
        </SearchTable>

        <div class="mx-auto mt20 flex justify-center">
            <el-button @click="close">
                取消
            </el-button>

            <SubmitBtn type="primary" @click="confirm">
                提交
            </SubmitBtn>
        </div>
    </PlusDialog>
</template>

<style lang="scss" scoped>
:deep(.vxe-header--row .vxe-checkbox--icon) {
    display: none;
}
</style>